import React, {
	createContext,
	forwardRef,
	ForwardRefRenderFunction,
	ReactElement,
} from 'react';
import useControlledState from '../hooks/use-controlled-state';
import { ForwardRefProps } from '../utils/interface';
import { classnames, createBEM } from '../utils/namespace';
import {
	RadioGroupContextData,
	RadioGroupProps,
	RadioValue,
} from './interface';

const NS = 'fnx-radio-group';
const bem = createBEM(NS);

export const RadioGroupContext = createContext<RadioGroupContextData>({});

const InternalRadioGroup: ForwardRefRenderFunction<
	HTMLDivElement,
	RadioGroupProps
> = (_props, ref) => {
	const {
		value: _value,
		defaultValue,
		onChange: _onChange,
		disabled,
		direction,
		iconSize,
		iconPosition,
		iconColor,
		iconShape,
		iconCheckedColor,
		labelDisabled,
		indicator,
		className,
		children,
		...resetProps
	} = _props;

	const { value, onChange } = useControlledState<RadioValue>({
		value: _value,
		defaultValue: defaultValue != null ? defaultValue : '',
		onChange: _onChange,
	});

	return (
		<div
			className={classnames(
				bem({
					...(direction != null
						? { [direction]: direction !== 'vertical' }
						: {}),
				}),
				className,
			)}
			{...resetProps}
			ref={ref}
		>
			<RadioGroupContext.Provider
				value={{
					value,
					disabled,
					direction,
					iconSize,
					iconPosition,
					iconColor,
					iconShape,
					iconCheckedColor,
					labelDisabled,
					indicator,
					onChange,
				}}
			>
				{children}
			</RadioGroupContext.Provider>
		</div>
	);
};

InternalRadioGroup.displayName = 'RadioGroup';

const RadioGroup = forwardRef<HTMLDivElement, RadioGroupProps>(
	InternalRadioGroup,
) as <T extends RadioValue = RadioValue>(
	props: ForwardRefProps<RadioGroupProps<T>, HTMLDivElement>,
) => ReactElement;

export default RadioGroup;
